package com.api.aiyh_quanshi.service.Impl;

import aiyh.utils.httpUtil.staticUtil.HttpStaticUtils;
import aiyh.utils.zwl.common.ToolUtil;
import com.alibaba.fastjson.JSONObject;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.weaverboot.frame.ioc.anno.classAnno.WeaIocReplaceComponent;
import com.weaverboot.frame.ioc.anno.methodAnno.WeaReplaceAfter;
import com.weaverboot.frame.ioc.anno.methodAnno.WeaReplaceBefore;
import com.weaverboot.frame.ioc.handler.replace.weaReplaceParam.impl.WeaAfterReplaceParam;
import com.weaverboot.frame.ioc.handler.replace.weaReplaceParam.impl.WeaBeforeReplaceParam;
import weaver.aiyh_quanshi.RequestApi;
import weaver.aiyh_quanshi.entity.QsConfParty;
import weaver.aiyh_quanshi.entity.QsResponse;
import weaver.conn.RecordSet;
import weaver.hrm.HrmUserVarify;
import weaver.hrm.User;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * 如不标注名称，则按类的全路径注入
 */
@WeaIocReplaceComponent("newMetingService")
public class NewMetingServiceImpl {
	ToolUtil toolUtil = new ToolUtil();
	RequestApi requestApi = new RequestApi();
	SimpleDateFormat simpleFormat = new SimpleDateFormat("yyyy-MM-dd hh:mm");
	QsResponse meting = null;
	private final Lock lock = new ReentrantLock();


	/**
	 * 这是接口前置方法，这个方法会在接口执行前执行
	 * 前值方法必须用@WeaReplaceBefore,这里面有两个参数，第一个叫value，是你的api地址
	 * 第二个参数叫order，如果你有很多方法拦截的是一个api，那么这个就决定了执行顺序
	 * 前置方法的参数为WeaBeforeReplaceParam 这个类，里面有四个参数，request，response，请求参数的map，api的地址
	 */
	@WeaReplaceBefore(value = "/api/meeting/base/newMeeting", order = 1, description = "会议接口前拦截")
	public void before(WeaBeforeReplaceParam weaBeforeReplaceParam) {
		try {
//			加锁
			lock.lock();
			RecordSet rs = new RecordSet();
			String query;
			// 同步会议到全时
//		String path = Objects.requireNonNull(this.getClass().getResource("")).getPath();
//		 获取请求参数
			Map paramMap = weaBeforeReplaceParam.getParamMap();
//		获取会议标题
			String title = String.valueOf(paramMap.get("name"));
//		会议内容
			String desc_n = String.valueOf(paramMap.get("desc_n"));
//		获取会议创建人
			String creator = String.valueOf(paramMap.get("contacter"));
//		获取会议创建人邮件
			query = "select * from hrmresource where id = ?";
			rs.executeQuery(query, creator);
			rs.next();
			String creatorEmail = rs.getString("email");
//		获取会议开始日期
			String startDate = String.valueOf(paramMap.get("begindate"));
//		获取会议开始时间
			String startTime = String.valueOf(paramMap.get("begintime"));
			Date start = simpleFormat.parse(startDate + " " + startTime);

//		获取会议结束日期
			String endDate = String.valueOf(paramMap.get("enddate"));
//		获取会议结束时间
			String endTime = String.valueOf(paramMap.get("endtime"));
			Date end = simpleFormat.parse(endDate + " " + endTime);

//		计算会议时长
			int length = new Long((end.getTime() - start.getTime()) / (1000 * 60)).intValue();
//		获取会议参与人
			String hrmStr = String.valueOf(paramMap.get("hrmmembers"));
//	    处理会议参与人
			List<QsConfParty> list = new ArrayList<>();
			query = "select * from hrmresource where id in ( " + hrmStr + ")";
			rs.executeQuery(query);
			while (rs.next()) {
				QsConfParty qsConfParty = new QsConfParty();
				qsConfParty.setEmail(rs.getString("email"));
				list.add(qsConfParty);
			}
			toolUtil.writeErrorLog(list.toString());
			toolUtil.writeErrorLog(String.valueOf(length));
//		调取接口
			meting = requestApi.createMeting(creatorEmail, title, length, startDate + " " + startTime + ":00 ", list);
			toolUtil.writeErrorLog(meting.toString());
			if (meting != null) {
//			请求失败
				if (!"0".equals(meting.getStatus())) {
					meting = null;
				}
			}
		} catch (Exception e) {
			toolUtil.writeErrorLog(e.toString());
		} finally {
			HttpStaticUtils.executorService.execute(() -> {
				try {
					Thread.sleep(20 * 1000);
				} catch (InterruptedException e) {
					e.printStackTrace();
				} finally {
					try {
						lock.unlock();
					} catch (IllegalMonitorStateException e) {
//						锁已经被释放
					}
				}
			});

		}
//		TODO 在after方法中更新会议id进入meting表中
	}

	/**
	 * apiCost: 688
	 * api_status: true
	 * meetingid: "8"
	 * retstatus: true
	 * status: true
	 * 这个是接口后置方法，大概的用法跟前置方法差不多，稍有差别
	 * 注解名称为WeaReplaceAfter
	 * 返回类型必须为String
	 * 参数叫WeaAfterReplaceParam，这个类前四个参数跟前置方法的那个相同，不同的是多了一个叫data的String，这个是那个接口执行完返回的报文
	 * 你可以对那个报文进行操作，然后在这个方法里return回去
	 */
	@WeaReplaceAfter(value = "/api/meeting/base/newMeeting", order = 1)
	public String after(WeaAfterReplaceParam weaAfterReplaceParam) {
		String data = weaAfterReplaceParam.getData();
		HttpServletRequest request = weaAfterReplaceParam.getRequest();
		HttpServletResponse response = weaAfterReplaceParam.getResponse();
		User user = HrmUserVarify.getUser(request, response);


		Map<String, Object> jsonObject = new HashMap<>();
		try {
			ObjectMapper mapper = new ObjectMapper();
			Map<String, Object> map = mapper.readValue(data, Map.class);

			if (map == null) {
				lock.unlock();
//			转换失败或数据为空
				return data;
			}
			if (Boolean.parseBoolean(String.valueOf(map.get("status")))) {
//			添加成功
				if (meting != null) {
//				更新全时会议id进入meting表中
					String update = "update meeting set quan_shi_id = ? where id = ?";
					RecordSet rs = new RecordSet();
					Map<String, Object> resultMap;
					resultMap = mapper.readValue(meting.getResult(), Map.class);
					rs.executeUpdate(update, String.valueOf(resultMap.get("conferenceId")), String.valueOf(map.get("meetingid")));
					toolUtil.writeErrorLog(resultMap.get("conferenceId") + " -:- " +
							resultMap.get("pcode1") + " -:- " + resultMap.get("pcode2") + " -:- " + map.get("meetingid"));
				} else {
//					添加失败
					toolUtil.writeErrorLog("添加失败！");
					jsonObject.put("api_status", false);
					jsonObject.put("api_errormsg", "全时会议添加失败！");
					lock.unlock();
					toolUtil.writeErrorLog(jsonObject.toString());
					return JSONObject.toJSONString(jsonObject);
				}
			}
			return jsonObject.toString();
		} catch (Exception e) {
			toolUtil.writeErrorLog(e.toString());
			jsonObject.put("api_status", false);
			jsonObject.put("api_errormsg", e.toString());
			return JSONObject.toJSONString(jsonObject);
		} finally {
			//		释放锁
			lock.unlock();
			toolUtil.writeErrorLog(data);
		}
	}
}